package com.mysoft.gfyx.marketdevelop.mip.agent;

import com.mysoft.framework.cache.api.CacheProvider;
import com.mysoft.framework.common.util.MappingUtil;
import com.mysoft.framework.modeling.dto.OptionItem;
import com.mysoft.gfyx.marketdevelop.mip.GetDeveloperDataService;
import com.mysoft.gfyx.marketdevelop.mip.agent.dto.InvenstmentRelationCacheDto;
import com.mysoft.gfyx.marketdevelop.mip.agent.dto.InvestmentItemDto;
import com.mysoft.gfyx.marketdevelop.mip.dto.*;
import com.mysoft.gfyx.marketdevelop.mip.dto.TjCustom.LandTagListRequestDto;
import com.mysoft.gfyx.marketdevelop.mip.dto.TjCustom.SqlApiResponseDto;
import com.mysoft.gfyx.marketdevelop.mip.dto.TjTag.GetAllTagResponseDto;
import com.mysoft.gfyx.marketdevelop.mip.dto.TjTag.GetTagClassListResponseDto;
import com.mysoft.gfyx.marketdevelop.service.CompanyService;
import com.mysoft.gfyx.marketdevelop.service.DeveloperService;
import com.mysoft.gfyx.marketdevelop.service.dto.TagDto;
import com.mysoft.gfyx.marketdevelop.service.dto.TagValuesListDto;
import feign.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class GetDeveloperDataServiceAgent {

    @Autowired
    private GetDeveloperDataService getDeveloperDataService;

    @Autowired
    private DeveloperService developerService;

    @Resource
    private CacheProvider cacheProvider;

    public BasicYcgListWithoutTotalResponseDto getInvestment(GetInvestmentRequestDto dto) {
        String cacheKey = "MARKETDEVELOP:INVESTMENTLIST:CREDITCODE:" + dto.getCredit_code();
        BasicYcgListWithoutTotalResponseDto res = cacheProvider.get(cacheKey);
        if (res != null) {
            return res;
        }

        res = getDeveloperDataService.getInvestment(dto);

        cacheProvider.set(cacheKey, res, 7200);

        return res;
    }

    public InvenstmentRelationCacheDto getFormativeInvestment(String creditCode) {
        String cacheKey = "MARKETDEVELOP:INVESTMENTLIST:CREDITCODE:" + creditCode;
        InvenstmentRelationCacheDto res = cacheProvider.get(cacheKey);
        if (res != null) {
            return res;
        }

        GetDeveloperFilterDataRequestDto dto = new GetDeveloperFilterDataRequestDto();
        dto = developerService.setCommonData(dto);
        dto.setDetail_table_name(DeveloperService.TABLE_INVESTMENT_RELATION);
        dto.setPage(1);
        dto.setPage_size(10000);
        dto.addFilterDtos("organizing_code", BaseTjFilterDto.OPERATE_EQUAL, creditCode, DeveloperService.TABLE_INVESTMENT_RELATION, BaseTjFilterDto.ASSOCIATE_NONE);

        BaseTjListResponseDto responseDto = getDeveloperDataService.getFilteredDeveloperDetailList(dto);
        res = new InvenstmentRelationCacheDto();
        ArrayList<InvestmentItemDto> resList = new ArrayList<>();

        if (responseDto.getData() == null || responseDto.getData().getList() == null || responseDto.getData().getList().size() == 0) {
            InvestmentItemDto investmentItemDto = this.getDefaultInvensmentRoot(creditCode);
            resList.add(investmentItemDto);
            res.setList(resList);
            cacheProvider.set(cacheKey, res, 7200);
            return res;
        }

        responseDto.getData().getList().forEach(investment -> {
            // 当数据异常的时候走这个逻辑
            if (investment.getItem().get("sub_organizing_code") == null) {
                if (resList.size() == 0) {
                    InvestmentItemDto investmentItemDto = this.getDefaultInvensmentRoot(creditCode);
                    resList.add(investmentItemDto);
                    return;
                }
            }

            InvestmentItemDto investmentItemDto = new InvestmentItemDto();

            investmentItemDto.setCreditCode(investment.getItem().get("sub_organizing_code").toString());

            if (investment.getItem().containsKey("sub_parent_organizing_code") && investment.getItem().get("sub_parent_organizing_code") != null) {
                String parentId = investment.getItem().get("sub_parent_organizing_code").toString();
                investmentItemDto.setParentCreditCode(parentId);
            } else {
                investmentItemDto.setParentCreditCode("");
            }

            investmentItemDto.setCompanyName(investment.getItem().get("sub_company_name").toString());
            String percentStr = investment.getItem().getOrDefault("parent_percent", "").toString();
            percentStr = "".equals(percentStr) ? "0.0" : percentStr;
            investmentItemDto.setPercent(Double.valueOf(percentStr));
            resList.add(investmentItemDto);
        });

        res.setList(resList);

        cacheProvider.set(cacheKey, res, 7200);
        return res;
    }

    protected InvestmentItemDto getDefaultInvensmentRoot(String creditCode) {
        InvestmentItemDto investmentItemDto = new InvestmentItemDto();
        investmentItemDto.setCreditCode(creditCode);
        investmentItemDto.setCompanyName("---");
        investmentItemDto.setParentCreditCode("");
        investmentItemDto.setPercent(100.0);
        return investmentItemDto;
    }

    public GetTagClassListResponseDto getTagClassList(String project, String entity_id) {
        String cacheKey = "MARKETDEVELOP:TJTAGCLASSLIST:ENTITYID:" + entity_id;
        GetTagClassListResponseDto res = cacheProvider.get(cacheKey);
        if (res != null) {
            return res;
        }

        res = getDeveloperDataService.getTagClassList(project, entity_id);
        return res;
    }

    public GetAllTagResponseDto getAllTagsAndValues(String project, String entity_id) {
        String cacheKey = "MARKETDEVELOP:TJTAGVALUELIST:ENTITYID:" + entity_id;
        GetAllTagResponseDto res = cacheProvider.get(cacheKey);
        if (res != null) {
            return res;
        }

        res = getDeveloperDataService.getAllTagsAndValues(project, entity_id);
        cacheProvider.set(cacheKey, res, 7200);
        return res;
    }

    public ArrayList<TagDto> getAllTags(String project, String entity_id) {
        String cacheKey = "MARKETDEVELOP:TJTAGLIST:ENTITYID:" + entity_id;
        ArrayList<TagDto> res = cacheProvider.get(cacheKey);
        if (res != null) {
            return res;
        }

        GetAllTagResponseDto allTagsAndValues = this.getAllTagsAndValues(project, entity_id);

        ArrayList<TagDto> cRes = new ArrayList<>();
        allTagsAndValues.getData().getUser_tag().forEach(t -> {
            TagDto tag = new TagDto();
            tag.setTag_id(t.getTag_id());
            tag.setTag_name(t.getTag_name());
            tag.setTag_name_en(t.getTag_name_en());
            List<TagValuesListDto> tagValuesListDtoList = MappingUtil.getSimpleMapperFacade().mapAsList(t.getValue_list(), TagValuesListDto.class);
            tag.setValue_list(tagValuesListDtoList);
            cRes.add(tag);
        });
        cacheProvider.set(cacheKey, cRes, 7200);
        return cRes;
    }

    public List<OptionItem> getIndustryTags() {
        String cacheKey = "MARKETDEVELOP:DEVELOPER:INDUSTRYTAG:";
        List<OptionItem> res = cacheProvider.get(cacheKey);
        if (res != null) {
            return res;
        }
        LandTagListRequestDto dto = new LandTagListRequestDto();
        dto.setPageSize(10000);
        SqlApiResponseDto industry = getDeveloperDataService.industryTagList(dto);
        List<OptionItem> industryTag = new ArrayList<>();
        Set<String> codeList = new HashSet<>();
        industry.getData().getRows().forEach(p -> {
            OptionItem itemBig = new OptionItem();
            if (!p.get("industry_category_big").equals("") && !codeList.contains(p.get("industry_category_big_code").toString())) {
                itemBig.setValue(p.get("industry_category_big_code").toString());
                itemBig.setText(p.get("industry_category_big").toString());
                industryTag.add(itemBig);
                codeList.add(p.get("industry_category_big_code").toString());
            }

            OptionItem itemMiddle = new OptionItem();
            if (!p.get("industry_category_middle").equals("") && !codeList.contains(p.get("industry_category_middle_code").toString())) {
                itemMiddle.setValue(p.get("industry_category_middle_code").toString());
                itemMiddle.setText(p.get("industry_category_middle").toString());
                itemMiddle.setParent(p.get("industry_category_big_code").toString());
                industryTag.add(itemMiddle);
                codeList.add(p.get("industry_category_middle_code").toString());
            }

            OptionItem itemSmall = new OptionItem();
            if (!p.get("industry_category_small").equals("") && !codeList.contains(p.get("industry_category_small_code").toString())) {
                itemSmall.setValue(p.get("industry_category_small_code").toString());
                itemSmall.setText(p.get("industry_category_small").toString());
                itemSmall.setParent(p.get("industry_category_middle_code").toString());
                industryTag.add(itemSmall);
                codeList.add(p.get("industry_category_small_code").toString());
            }

        });
        cacheProvider.set(cacheKey, industryTag, 7200);
        return industryTag;
    }
}
